public class Solution110 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    boolean flag=true;

    public boolean isBalanced(TreeNode root) {
        dfs(root);
        return flag;
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int l=dfs(root.left);
        int r=dfs(root.right);
        if (Math.abs(l-r)>1){
            flag=false;
        }
        return Math.max(l,r)+1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution110().isBalanced(new TreeNode(3,new TreeNode(9),new TreeNode(20,new TreeNode(15),new TreeNode(7)))));
    }
}
